package com.foreveross.eimpc.web.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.Map;

@SuppressWarnings({"unchecked", "rawtypes"})
public class FastJsonUtil {

    private static final SerializerFeature[] features = {
            SerializerFeature.WriteMapNullValue, // 输出空置字段
            SerializerFeature.WriteDateUseDateFormat,  //日期类型字段输出
            SerializerFeature.WriteNullListAsEmpty, // list字段如果为null，输出为[]，而不是null
            SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null，输出为0，而不是null
            SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null，输出为false，而不是null
            SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null，输出为""，而不是null
    };

    private static final SerializeConfig config;

    static {
        config = new SerializeConfig();
        config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
        config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
    }

    /**
     * 从json字符串中解析出java对象
     *
     * @param jsonStr json格式字符串
     * @param clazz   java类
     * @return clazz的实例
     * @author:wuxiaoxue
     * @createTime:2012-7-8
     */

    public static Object parseJavaObject(String jsonStr, Class clazz) {

        return JSON.toJavaObject(JSON.parseObject(jsonStr), clazz);

    }

    /**
     * 序列化为和JSON-LIB兼容的字符串
     *
     * @param java 对象Object
     * @return String
     * @author:wuxiaoxue
     * @createTime:2012-7-8
     */

    public static String getJSONString(Object object) {

        return JSON.toJSONString(object, features);

    }


    public static void main(String[] arg) throws Exception {
        String s = "{status : 'success'}";
        System.out.println(" object : " + ((Map) parseJavaObject(s, Map.class)).get("status"));
    }

}
